package parse;

import org.apache.commons.digester.Digester;
import org.apache.commons.digester.xmlrules.DigesterLoader;
import org.xml.sax.SAXException;

import java.io.IOException;

/**
 * @author 石小俊
 */
public class DigesterParse {

    public static void main(String[] args) {
        // 获取解析器
        // 解析rule.xml文件,建立XML与Java对象的关系
        Digester digester = DigesterLoader.createDigester(DigesterParse.class.getClassLoader().getResource("parse/rule.xml"));

        // 准备一个空对象,用于接收解析器的结果,该对象必须是根标签所对应的Java对象
        ClassBean classBean = new ClassBean();

        // 将该对象交给解析器
        digester.push(classBean);

        try {
            System.out.println("解析前:"+classBean);
            // 解析
            digester.parse(DigesterParse.class.getClassLoader().getResourceAsStream("students.xml"));
            System.out.println("解析后:"+classBean);
            System.out.println("学号为1的学生姓名:"+classBean.findStudent("1").getName());
            System.out.println("学号为2的学生姓名:"+classBean.findStudent("2").getName());
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (SAXException e) {
            throw new RuntimeException(e);
        }

    }

}
